import Taro, { Component } from '@tarojs/taro';
import { View, Image, Text, Label ,Button} from '@doctorwork/components';
import { Canvas } from '@tarojs/components';
import { connect } from '@tarojs/redux';
import { rewriteAddMTA } from './../../model/utils/rewrite';
import { qqmapKey } from '../../model/api';
import sensor from '../../utils/sa';
import './index.styl';

@connect(({ index }) => ({
    ...index
}))
@rewriteAddMTA
export default class Index extends Component {
    constructor(props){
        super(props);
        this.state = {
            showPrivacy: false,
            city: null,
            showFaval: false,
            showGroupModal: false
        };
    }
    config = {
        navigationBarTitleText: '加油记录助手',
        navigationStyle: 'default',
        usingComponents: {
            'uweather': '../../components/uweather/index',
            'privacy-popup': '../../components/privacyPopup/index',
        }
    };
    
    componentDidMount(){
        const favaled = wx.getStorageSync('favaled');
        this.setState({showFaval: !favaled});
        // this.getUserLocation();
    }
    /**
     * 初始化隐私协议
     */
    initPrivacy(){
        if(wx.getPrivacySetting){
            wx.getPrivacySetting({
                success: res => {
                    console.log('是否需要授权：', res.needAuthorization, '隐私协议的名称为：', res.privacyContractName);
                    if (res.needAuthorization) {
                        this.setState({
                            showPrivacy: true
                        });
                    } 
                },
                fail: () => { },
                complete: () => { },
            });
        }
    }
    /**
     * 获取用户经纬度
     */
    async getUserLocation(){
        const userPosition = await this.getLocation();
        const userAddr = await this.locationToAddress(userPosition);
        const {address, location} = userAddr ||{};
        const province = address.split('省')[0];
        let city = address.split('市')[0];
        city = city.split('省')[1];
        wx.setStorageSync('province', province);
        wx.setStorageSync('city', city);
        wx.setStorageSync('location', JSON.stringify(location));
        this.setState({
            city
        });
    }
    getLocation(){
        return new Promise((resolve)=>{
            wx.getLocation({
                type: 'gcj02',
                isHighAccuracy: true,
                success (res) {
                    resolve(res);
                },
                fail: e => {
                    console.error('地理位置获取失败:',e);
                    wx.getStorageSync('province')||'北京';
                    wx.setStorageSync('location', JSON.stringify({}));
                }
            });
        });
    }
    /**
     * 经纬度转位置
     */
    locationToAddress(address){
        return new Promise((resolve, reject) => {
            wx.request({
                url: 'https://apis.map.qq.com/ws/geocoder/v1/',
                method: 'GET',
                data: {
                    coord_type: 5,
                    get_poi: 0,
                    output: 'json',
                    key: qqmapKey,
                    location: `${address.latitude},${address.longitude}`
                },
                success: (res)=>{
                    console.log(res);
                    const {statusCode, data} = res;
                    if(statusCode == 200){
                        const result = data.result ||{};
                        const location = {
                            latitude: result.location.lat,
                            longitude: result.location.lng
                        };
                        resolve({
                            address: result.address,
                            location: location
                        });
                    }
                },
                fail: (e)=> {
                    console.log(e);
                    reject(e);
                }
            });
        });
    }
    favaledClick(){
        wx.setStorageSync('favaled', true);
        this.setState({showFaval: false});
    }

    componentDidShow() {
        this.props.dispatch({
            type : 'index/init'
        });
        this.initPrivacy();
    }

    /**
     * 同意隐私协议
     */
    agreeClick(){
        console.log('同意了');
        this.setState({showPrivacy: false});
    }
    /**
     * 拒绝隐私协议
     */
    onRefuse(){
        this.setState({showPrivacy: false});
    }
    

    jumpAdd(){
        this.props.dispatch({
            type : '$router/forward',
            payload : {
                url : '/pages/create/index',
            }
        });
    }
    jumpStation(){
        this.props.dispatch({
            type : '$router/forward',
            payload : {
                url : '/pages/station/index',
            }
        });
    }

    showMoreTips(){
        // this.props.dispatch({
        //     type : '$router/forward',
        //     payload : {
        //         url : '/pages/tipList/index',
        //     }
        // });
    }
    
    jumpDetail(id){
        this.props.dispatch({
            type : '$router/forward',
            payload : {
                url : `/pages/detail/index?id=${id}`,
            }
        });
    }

    goTipDetail(){
        const {tip} = this.props;
        this.props.dispatch({
            type : '$router/forward',
            payload : {
                url : `/pages/tipDetail/index?id=${tip.id}`,
            }
        });
    }
    // 跳转到我的保养页面
    goMaintenance(){
        const {tip} = this.props;
        this.props.dispatch({
            type : '$router/forward',
            payload : {
                url : '/pages/maintenance/index',
            }
        });
    }

    
    /**
     * 展示今日油价
     */
    showPrice(){
        this.props.dispatch({
            type: '$router/forward',
            payload: {
                url: '/pages/price/index'
            }
        });
    }
    /**
     * 订阅涨价提醒
     */
    subscribeNotice(){
        wx.requestSubscribeMessage({
            tmplIds: ['VoBqNu9Np3YYpSonKOEvo8ptwOChdxLL5OZqMiWZLvE'],
            success (res) {
                console.log('订阅成功');
            }
        });
    }
    /**
     * 其他记账项目
     */
    jumpRecord(){
        this.props.dispatch({
            type: '$router/forward',
            payload: {
                url: '/pages/recordList/index'
            }
        });
    }
    /**
     * 导航栏跳转
     * @param {*} url 
     */
    goNaviItem(url){
        this.props.dispatch({
            type: '$router/forward',
            payload: { url }
        });
    }
    onShareAppMessage(){
        const {notice} = this.props;
        const open_id = wx.getStorageSync('open_id');
        sensor.track('页面分享',{
            $element_name : open_id
        });
        return {
            title: notice,
            path: 'pages/index/index'
        };
    }
    /**
     * 展示弹窗
     */
    showGroupChat(){
        // const {showGroupModal} = this.state;
        // this.setState({
        //     showGroupModal: !showGroupModal
        // });
        wx.navigateToMiniProgram({appId: 'wx3162047023d4257c'});
    }
    stopEvent(e) {
        e.stopPropagation();
    }



    render() {
        const {showGroupModal,showFaval,city,showPrivacy} = this.state;
        const {list,showTips,notice, count, tip, allData,series,config} = this.props;

        return (
            <View className='container'>
                {/* <Navigate
                    title='加油记录助手'
                    color='black'
                    backgroundColor='white'
                    backTextColor='black'
                /> */}


                {/* -----------------顶部说明------------------- */}
                <View className='header'>
                    <View className='desc'>记录您的爱车日常消费、计算油耗、油价趋势提醒、车友交流、全国油价查询、汽车小知识、附近加油站等</View>
                </View>
                {/* -----------------功能入口------------------- */}
                <View className='card'>
                    <View>
                        {
                            series.map(item => (<View><Label className='type'>{item.name}:</Label>{item.data}元</View>))
                        }
                    </View>
                    <View>
                        {
                            !showPrivacy && <View class='mychart-view'>
                                <Canvas canvas-id='areaCanvas' disable-scroll='true' class='canvas' style={{display: showGroupModal ? 'none': 'block'}}></Canvas>
                            </View>
                        }
                        
                    </View>
                </View>
                <View className='tip-item' >
                    <View className='item health' onClick={this.jumpAdd.bind(this)} data-name='记一笔'><Label>记一笔</Label><Text className='text'  >加完油记录一下</Text></View>
                    <View className='item coupon'  onClick={this.goMaintenance.bind(this)} data-name='保养记录'><Label>保养记录</Label><Text className='text'>记录保养信息</Text></View>
                    <View className='item doctor' onClick={this.jumpRecord.bind(this)} data-name='日常记录'><Label>日常记录</Label><Text className='text' >过路费、停车费</Text></View>
                </View>
                {/* 导航栏 */}
                <View className='navigator'>
                    
                    <View className='nav-item' onClick={this.goNaviItem.bind(this, '/pages/price/index')}>
                        <Image src={require('./imgs/price.png')} className='icon'></Image>
                        <View className='nav-desc'>今日油价</View>
                    </View>
                    {/* <View className='nav-item' onClick={this.goNaviItem.bind(this, '/pages/station/index')}>
                        <Image src={require('./imgs/station.png')} className='icon'></Image>
                        <View className='nav-desc'>附近加油站</View>
                    </View> */}
                    {/* {
                        showTips && <View className='nav-item' onClick={this.goNaviItem.bind(this, '/pages/tipList/index')}>
                            <Image src={require('./imgs/tips.png')} className='icon'></Image>
                            <View className='nav-desc'>小知识</View>
                        </View>
                    } */}
                    <View className='nav-item' onClick={this.showGroupChat.bind(this)}>
                        <Image src={require('./imgs/chat.png')} className='icon'></Image>
                        <View className='nav-desc'>休息一下</View>
                    </View>
                    
                </View>
                <View className='section'>
                    <View className='oil-title'>
                        <View className='segace'></View>
                        调价提醒
                    </View>
                    {
                        notice && <View className='notice'>{notice}
                            {/* <Label onClick={this.subscribeNotice.bind(this)}>明天提醒我</Label> */}
                            <Button className='link' OpenType='share' data-name='查看今日油价'> 分享给好友<Image className='share' src={require('./imgs/share.png')}></Image></Button>
                        </View>
                    }
                </View>
                {/* -------------------汽车小知识----------------- */}
                {
                    tip && <View className='section'>
                        {/* <View className='oil-add'>
                        <Text className='iconfont icon-right oil-add-btn'  onClick={this.jumpAdd.bind(this)}>&#xe621;</Text>
                    </View> */}
                        <View className='oil-title'>
                            <View className='segace'></View>
                        每日小知识
                            {/* {
                                count > 1 && <View className='show-more' onClick={this.showMoreTips.bind(this)} data-name='查看更多'>查看更多 > </View>
                            } */}
                        </View>
                        <View className='welcome'>欢迎您的到来,已累计登录<Label>{count}</Label>天, 每天登录都可以学习一条汽车小知识哦 ! 今日内容:  </View>
                        <View className='notice'>
                            <View className='oil-carNumber'>{tip && tip.title}
                                <Label onClick={this.goTipDetail.bind(this)} data-name='查看详情'>查看详情 ></Label>
                            </View>
                            <View className='oil-time'>{tip.content}</View>
                        </View>
                    </View>
                }
                {
                    city &&<View className='oil-title'>
                        <View className='segace'></View>
                        天气情况
                    </View>
                }
                {
                    city && <uweather city={city} ></uweather>
                }
                
                {
                    showGroupModal && <View className='qrcode-modal' onClick={this.showGroupChat.bind(this)}>
                        <View className='content' onClick={this.stopEvent.bind(this)}>
                            <View className='text'>长按识别二维码或保存到本地</View>
                            <Image className='qrcode' show-menu-by-longpress src={config.chatLink}></Image>
                        </View>
                    </View>
                }
                {
                    showFaval && <View className='add-tip' onClick={this.favaledClick.bind(this)}>
                        <View className='add-item'>点击<Image class='small-dot'></Image><Image class='large-dot'></Image><Image class='small-dot'></Image>添加到我的小程序</View>
                        <View className='add-item'>微信首页下拉快速访问</View>
                        <Image className='triggle' src={require('./imgs/triggle.png')}></Image>
                        <Image className='close' src={require('./imgs/close.png')}></Image>
                    </View>
                }
                
                

                {
                    showPrivacy && <privacy-popup onAgree={this.agreeClick.bind(this)} onRefuse={this.onRefuse.bind(this)}></privacy-popup>
                }
                
            </View>

        );
    }
}
